package com.apes.fn.server.workDesk.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.report.util.SalesReportUtils;
import com.apes.fn.server.workDesk.repository.WorkDeskDao;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.hr.base.model.Employee;
import com.apes.hr.base.repository.EmployeeRepository;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.rbac.model.Post;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.PostRepository;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @program: apes-server
 * @description: 新版工作台
 * @author: czs
 * @create: 2023-06-08 10:17
 **/
@Service("workDeskService")
public class WorkDeskService extends DomainService {

    @Autowired
    private WorkDeskDao workDeskDao;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 门店当天销售业绩
     * @param request
     * @return Json
     * @author czs
     * @creed: 入参需要DEPT_ID
     * @date
     */
    public JSONObject deptSalesReportDetail(SimpleRequest request){
        JSONObject jo = request.getJO();
        JSONArray array = null;
        boolean canSee = false ;//是否允许查看毛利
        try {
            //主数据
            if (jo.containsKey("DEPT"))jo.put("DEPT_ID",jo.get("DEPT"));
            array = workDeskDao.deptSalesReportDetail(jo);
        } catch (Exception e) {
            array= new JSONArray();
        }
        try{
            //查岗位
            if (request.getSession()==null){
                throw new RuntimeException("当前登录人员不存在");
            }
            Post post = SpringManager.getBean(PostRepository.class).findOne(request.getPostId());
            String id = post.getWorkPost().getPostGroup().getId();
            if ("0004".equals(id))canSee = true;//0004为店长组
            if (post.getDept().getCompany().getParty().getCorporate().getOperation().getId().equals("001072"))canSee = false;//直营不允许
        } catch(Exception e) {
            return SalesReportUtils.filterJson(
                    new JSONObject(),
                    "SALE_MONEY", "SALE_MONEY",
                    "TIMES", "TIMES",
                    "NEW_CLIENT", "NEW_CLIENT",
                    "YEARCARD", "YEARCARD"
            );
        }

        if (array.isEmpty())array.add(new JSONObject());
        //调用APP数据 获取返回结果data
        JSONArray data = null;
        try {
            JSONObject response = JSONObject.parseObject(this.invoke("pi.app.ext",
                    MapUtil.mapper("headers",MapUtil.mapper("method","v1/store-data/statistical-data","action","get"),
                            "body",mapper("storeCode",jo.getString("DEPT_ID"),"typeList","newMember"))
            ));
            data = response.getJSONArray("data");

        } catch (Exception e) {
            e.printStackTrace();
            Document document = new Document();
            document.put("DEPT_ID", jo.get("DEPT_ID"));
            document.put("data", jo);
            document.put("session", request.getSession().getSessionId());
            document.put("post", request.getSession().getPostId());
            document.put("user", request.getSession().getUserId());
            document.put("errInfo",e.getMessage());
            document.put("method","deptSalesReportDetail");
            if (!e.getMessage().contains("请检查连接、参数是否正确"))mongoTemplate.getCollection("smartHelperError").insertOne(document);
            throw new RuntimeException("查询门店数据有误:"+e.getMessage());
        }

        JSONObject jsonObject;
        if (canSee){
            //仅店长允许查看成本和毛利
            jsonObject = SalesReportUtils.filterJson(
                    array.getJSONObject(0),
                    "SALE_MONEY", "SALE_MONEY",
                    "COST", "COST",
                    "TIMES", "TIMES",
                    "YEARCARD", "YEARCARD",
                    "PROFIT", "PROFIT"
            );
        }else {
            jsonObject = SalesReportUtils.filterJson(
                    array.getJSONObject(0),
                    "SALE_MONEY", "SALE_MONEY",
                    "TIMES", "TIMES",
                    "YEARCARD", "YEARCARD"
            );
        }
        jsonObject.put("NEW_CLIENT",data==null?0:data.getJSONObject(0).get("value"));

        return jsonObject;
    }
    /**
     * 人员当天产值
     * @param request
     * @return Json
     * @author czs
     * @creed: 入参需要DEPT_ID,会话
     * @date
     */
    public JSONObject personSalesRpeortDetail(SimpleRequest request){
        JSONObject jo = request.getJO();
        PartyRole person = request.getPerson();
        if (person==null){
            return new JSONObject();
        }
        Employee employee = SpringManager.getBean(EmployeeRepository.class).findByOrigin(person.getId());
        jo.put("PARTY_ROLE_ID",person.getId());
//        jo.put("PARTY_ROLE_ID","0001579");
        JSONArray array = null;
        try {
            array = workDeskDao.personSalesRpeortDetail(jo);
        } catch (Exception e) {
            array = new JSONArray();
        }
        if (array.isEmpty())array.add(mapper(
                "DEPT_NAME", jo.getString("DEPT_ID")==null?"":SpringManager.getBean(DeptRepository.class).findOne(jo.getString("DEPT_ID")).getName(),
                "PARTY_ROLE_NAME", person.getName(),
                "SEX", employee==null?null:employee.getSex().getDescription()
        ));
        JSONObject jsonObject = SalesReportUtils.filterJson(
                array.getJSONObject(0),
                "PARTY_ROLE_NAME", "PARTY_ROLE_NAME",
                "DEPT_NAME", "DEPT_NAME",
                "CZPM", "CZPM",
                "TC", "TC",
                "CZ", "CZ",
                "SEX","SEX"
        );
        if ("0".equals(jsonObject.getString("CZPM")))jsonObject.put("CZPM","");
        return jsonObject;
    }
}
